﻿/**
    作者：张峰
    版本：AS3.0

    功能：绑定中文字库。

*/
package zf.data.tools
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.system.ApplicationDomain;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFormat;

	/**
	 * 绑定中文字库类 ，按下面步骤：
	 * 1.做好共享字体库并作为共享库链接  
	 * 2.查看载入的SWF文件名，及其字体链接名  
	 * 3.TextField.embedFonts=true  
	 * 4.TextFormat.font=Font.enumerateFonts(false)[0].fontName
	 * @author mike.zhang
	 * @langversion 3.0 
	 * @playerversion Flash 9 
	 */
	public class embedChinese extends EventDispatcher
	{
		private var _loader:Loader;
		private var _tfname:String;
		/**
		 * 创建一个中文字符绑定 
		 * @param url 字库绑定用SWF文件地址
		 * @param fontName 字体名(链接名)
		 * 
		 */
		public function embedChinese (url:String,fontName:String):void
		{
			_tfname=fontName;
			try
			{
				_loader=new Loader();
				_loader.contentLoaderInfo.addEventListener (Event.COMPLETE,completeHandler);
				_loader.load (new URLRequest(url));
			}
			catch (e:Error)
			{
				throw new Error("not find \""+url+"\"");
			}
		}
		private function completeHandler (e:Event):void
		{
			try
			{
				var fontLibrary:Class=e.target.applicationDomain.getDefinition(_tfname) as Class;
				Font.registerFont (fontLibrary);
				e.stopPropagation();
				dispatchEvent (new Event(Event.COMPLETE));
			}
			catch (e:Error)
			{
				throw new Error("not find font: " + _tfname);
			}
		}
		/**
		 * 获取载入的字库数组，其每个元素用于 给TextFormat.font赋值
		 * @return 数组
		 * 
		 */
		public function get FontArray ():Array
		{
			return Font.enumerateFonts(false);
		}
	}
}